
<template>
    <div class="quill-editor-container" v-loading="loading">
        <quill-editor
            v-if="showEditor"
            v-model="content"
            :options="editorOption"
            @change="onEditorChange($event)">
        </quill-editor>
    </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { getRouters } from '@/api/getData';
import { quillEditor,Quill } from 'vue-quill-editor'
import common from "@/api/api";
const toolbar = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ['blockquote', 'code-block'], // 引用  代码块-----['blockquote', 'code-block']
  [{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ script: 'sub' }, { script: 'super' }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{ indent: '-1' }, { indent: '+1' }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{'direction': 'rtl'}], // 文本方向-----[{'direction': 'rtl'}]  console.log(val)  console.log(val)
  [{ size: ['small', false, 'large', 'huge'] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{ font: [] }], // 字体种类-----[{ font: [] }]
  [{ align: [] }], // 对齐方式-----[{ align: [] }]
  ['clean'], // 清除文本格式-----['clean']
  ['image'] // 链接、图片、视频-----['link', 'image', 'video']
]
const Delta = Quill.import('delta')
export default {
    name: 'QuillEditor',
    components: {
        quillEditor
    },
    props: {
        value: {
            type: String,
            default: '',
        }
    },
    data () {
        return {
            showEditor: false,
            loading:false,
            imgSign: {},
            content: this.value || '',
            editorOption: {}
        }
    },
    watch: {
        value(val) {
            this.content = val;
        },
    },
    mounted () {
        this.getImgSign()
    },
    methods: {
        // 获取图片上传签名（因为上传到腾讯云，所以要一些额外参数）
        getImgSign() {
            getRouters().then(({ data }) => {
                this.imgSign = data
                this.setEditorOption()
            })
        },
        loadingShow(){
        	this.loading = true;
        	console.log('show');
        },
        loadingHide(){
        	this.loading = false;
        	console.log('hide');
        },
        // 设置配置信息
        setEditorOption() {
            // 当前组件实例
            let vm = this
            this.editorOption = Object.assign(this.editorOption, {
                placeholder: '请插入内容...',
                modules: {
                    toolbar: {
                        container: toolbar,
                         handlers: {
                            // 自定义上传图片到服务器
                            image: function() {
                            		let lengths = 0;
                                // quill插件实例
                                let _self = this
                                // 创建上传文件input并触发
                                let fileInput = document.createElement('input')
                                fileInput.setAttribute('type', 'file')
                                fileInput.setAttribute('multiple', 'multiple')
                                fileInput.setAttribute('accept', 'image/*')
                                fileInput.addEventListener('change', () => {
                                    if (fileInput.files !== null) {
                                        const files = Array.from(fileInput.files);
                                        console.log(files);
                                        // 利用es6迭代器异步顺序上传图片，保证图片插入顺序正常
                                        const it = files[Symbol.iterator]();
                                        uploadFile()

                                        function uploadFile () {

                                           const { done, value: _file } = it.next()
                                            if (done) return
                                            let reader = new FileReader()
                                            reader.onload = (event) => {
                                            		vm.loadingShow();
                                                const range = _self.quill.getSelection(true)
                                                // 设置图片上传地址
                                                const uploadImgServer = common.apihost+'/system/file/uploadFile'
                                                // 创建formData参数提交（文件+签名信息）
                                                const formData = new FormData();
                                                console.log(_file)
                                                formData.append('file', _file)
                                                formData.append('fileType', '1')
                                                // 发送图片上传请求
                                                const xhr = new XMLHttpRequest()
                                                xhr.open('POST', uploadImgServer)
                                                xhr.timeout = 60000
                                                xhr.setRequestHeader('AuthorizationMegaStoer', localStorage.getItem('appToken'));
                                                xhr.ontimeout = () => {
                                                	vm.$message.error('图片上传超时');
                                                	 vm.loadingHide();
                                                }
                                                xhr.onreadystatechange = () => {
                                                    let result
                                                    vm.loadingHide();
                                                    if (xhr.readyState === 4) {
                                                        // http status code
                                                        if (xhr.status < 200 || xhr.status >= 300) {
                                                        	vm.$message.error(`上传图片发生错误，上传图片发生错误，服务器返回状态是 ${xhr.status}`);
                                                        }
                                                        result = xhr.responseText
                                                        if (typeof result !== 'object') {
                                                            try {
                                                                result = JSON.parse(result)
                                                            } catch {
                                                            	vm.$message.error('上传图片失败', '上传图片返回结果错误，返回结果是: ' + result);
                                                            }
                                                        }
                                                        const URI = result?result.data.fullFilename:'';
																							          let length = _self.quill.getSelection().index;
																							          _self.quill.insertEmbed(length, 'image', URI);
																							          _self.quill.setSelection(length + 1);
																						            uploadFile();

                                                    }



                                                }
                                                xhr.send(formData)
                                            }
                                            reader.readAsDataURL(_file)
                                        }
                                    }
                                })
                                fileInput.click()
                            }
                        }
                    }
                }
            })
            this.$nextTick(() => {
                this.showEditor = true
            })
        },
        // 文本改变后同步回父组件绑定的值
        onEditorChange(event) {
          console.log(event)
            this.$emit('update:value', event.html)
        }
    }


}
</script>
<style lang="scss" scoped>
 .quill-editor-container /deep/ .quill-editor  .ql-container {
        height: 720px;
    }
</style>
